package com.im.service.jim.processor;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.im.service.domain.dto.UnreadMsg;
import com.im.service.domain.entity.ImChat;
import com.im.service.domain.message.Signalling;
import com.im.service.jim.ChatSessionUtil;
import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import static com.im.service.service.impl.ImChatServiceImpl.userChat;

/**
 * @author liuzhiqiang
 */
public class BoundSessionProcessor extends AbstractCmdHandler {

    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Command command() {
        return Command.BOUND_SESSION;
    }

    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) {
        try {
            String body = new String(imPacket.getBody(), ImConst.CHARSET);
            Signalling signalling = JSONUtil.toBean(body, Signalling.class);
            imChannelContext.set("chatId", signalling.getData());
            if (redisTemplate != null) {
                HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
                String userId = imChannelContext.getUserId();
                String chat = hashOperations.get(userChat + StrPool.COLON + userId, signalling.getData());
                if (StrUtil.isNotBlank(chat)) {
                    ImChat imChat = JSONUtil.toBean(chat, ImChat.class);
                    imChat.setUnreadQuantity(0);
                    hashOperations.put(userChat + StrPool.COLON + userId, signalling.getData(), JSONUtil.toJsonStr(imChat));

                    // 推送给操作方,当前会话已读未回消息
                    List<String> unreadMsgIdList = new ArrayList<>();
                    if (StrUtil.isNotBlank(imChat.getUnreadMsgIds())) {
                        unreadMsgIdList = JSONUtil.toList(imChat.getUnreadMsgIds(), String.class);
                    }
                    ImPacket unreadImPacket = new ImPacket();
                    unreadImPacket.setStatus(ImStatus.C10000);
                    unreadImPacket.setCommand(Command.UNREAD_MSG_IDS);
                    UnreadMsg unreadMsg = new UnreadMsg(Long.parseLong(signalling.getData()), unreadMsgIdList);
                    unreadImPacket.setBody(new RespBody(Command.UNREAD_MSG_IDS, unreadMsg).toByte());
                    JimServerAPI.send(imChannelContext, unreadImPacket);

                    // 推送给对方,当前会话消息已读
                    String targetId = signalling.getData();
                    String targetChatStr = hashOperations.get(userChat + StrPool.COLON + targetId, userId);
                    if (StrUtil.isNotBlank(targetChatStr)) {
                        ImChat targetChat = JSONUtil.toBean(targetChatStr, ImChat.class);
                        targetChat.setUnreadMsgIds("[]");
                        hashOperations.put(userChat + StrPool.COLON + targetId, userId, JSONUtil.toJsonStr(targetChat));
                        UnreadMsg unreadMsgTwo = new UnreadMsg(Long.parseLong(userId), ListUtil.empty());
                        unreadImPacket.setBody(new RespBody(Command.UNREAD_MSG_IDS, unreadMsgTwo).toByte());

                        // 给和我保持会话的对方通道推送
                        List<ImChannelContext> list = JimServerAPI.getByUserId(targetId);
                        for (ImChannelContext channelContext : list) {
                            Object chatId = channelContext.get("chatId");
                            if (chatId != null && StrUtil.equals(chatId.toString(), userId)) {
                                JimServerAPI.send(channelContext, unreadImPacket);
                            }
                        }
                    }
                }
            }
            ChatSessionUtil.sendNewSessionToUser(imChannelContext.getUserId());

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
